#include "requestmapper.h"
#include "global.h"

RequestMapper::RequestMapper(QObject *parent)
    : HttpRequestHandler(parent)
{

}

void RequestMapper::service(HttpRequest &request, HttpResponse &response)
{
    QByteArray path = request.getPath();
    qDebug("RequestMapper: path=%s", path.data());

    HttpSession session = sessionStore->getSession(request, response, false);
    QString username = session.get("username").toString();
    logger->set("currentUser", username);

    QByteArray sessionId = sessionStore->getSessionId(request, response);
    if (sessionId.isEmpty() && path != "/login") {
        qDebug("RequestMapper: redirect to login page");
        response.redirect("/login");
        return;
    } else if (path == "/" || path == "/hello") {
        helloWorldController.service(request, response);
    } else if (path == "/list") {
        listDataController.service(request, response);
    } else if (path == "/list2") {
        dataTemplateController.service(request, response);
    } else if (path == "/login") {
        loginController.service(request, response);
    } else if (path == "/cookie") {
        cookieTestController.service(request, response);
    } else if (path.startsWith("/files")) {
        staticFileController->service(request, response);
    } else {
        response.setStatus(404, "Not found");
        response.write("The URL is wrong, no such document.", true);
    }
    qDebug("RequestMapper: finished request");
    logger->clear(true, true);
}
